package com.stylefeng.guns.modular.wz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.Consts;
import com.stylefeng.guns.common.constant.factory.PageFactory;
import com.stylefeng.guns.common.persistence.dao.*;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.wz.dao.WzAdvDao;
import com.stylefeng.guns.modular.wz.service.IWzAdvService;
import com.stylefeng.guns.modular.wz.util.DateUtil;
import com.stylefeng.guns.modular.wz.warpper.PfFileWarpper;
import com.stylefeng.guns.modular.wz.warpper.WzAdvWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.stylefeng.guns.modular.wz.util.DateUtil.format_ymdhms;

/**
 * 广告控制器
 *
 * @author fengshuonan
 * @Date 2018-03-20 09:41:34
 */
@Controller
@RequestMapping("/wzAdv")
public class WzAdvController extends BaseController {
    private String PREFIX = "/wz/wzAdv/";

    @Autowired
    private IWzAdvService wzAdvService;
    @Autowired
    private WzAdvDao wzAdvDao;
    @Autowired
    private PfFileMapper pfFileMapper;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzQuestionnaireMapper questionnaireMapper;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private PfOpenCityMapper openCityMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;

    /**
     * 跳转到广告首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "wzAdv.html";
    }

    /**
     * 跳转到添加广告
     */
    @RequestMapping("/wzAdv_add")
    public String wzAdvAdd() {
        return PREFIX + "wzAdv_add.html";
    }

    /**
     * 跳转到添加广告2
     */
    @RequestMapping("/wzAdv_add_tab")
    public String wzAdvAddTab() {
        return PREFIX + "wzAdv_add_tab.html";
    }

    /**
     * 跳转到修改广告
     */
    @RequestMapping("/wzAdv_update/{wzAdvId}")
    public String wzAdvUpdate(@PathVariable Long wzAdvId, Model model) {
        WzAdv wzAdv = wzAdvService.selectById(wzAdvId);
        model.addAttribute("item", wzAdv);
        model.addAttribute("beginTime", DateUtil.toString(wzAdv.getBeginTime(), format_ymdhms));
        model.addAttribute("endTime", DateUtil.toString(wzAdv.getEndTime(), format_ymdhms));
        LogObjectHolder.me().set(wzAdv);
        String details = wzAdv.getAdvDetail();
        details = details.replaceAll("& lt;", "<");
        details = details.replaceAll("& gt;", ">");
        model.addAttribute("details", details);
        model.addAttribute("coverUrl", Consts.DOMAIN+wzAdv.getCoverUrl());
        return PREFIX + "wzAdv_edit.html";
    }


    /**
     * 获取广告列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        Page<WzAdv> page = new PageFactory<WzAdv>().defaultPage();
        List<Map<String, Object>> list = advMapper.selectMapsPage(page, new EntityWrapper<WzAdv>().like("title",condition).orderBy("status",true).orderBy("create_time",false));
        page.setRecords((List<WzAdv>) new WzAdvWarpper(list).warp());
        return super.packForBT(page);
    }

    /**
     * 获取到添加广告时的优惠券等id
     */
//            session.setAttribute("details", details.replaceAll("& #39;", "'"));

    /**
     * 新增广告
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(WzAdv wzAdv,String begin,String end){
        wzAdv.setExpense(wzAdv.getExpense()*100);
        wzAdv.setTotalReward(wzAdv.getTotalReward()*100);
        wzAdv.setBeginTime(DateUtil.toDateTime(begin));
        wzAdv.setEndTime(DateUtil.toDateTime(end));
        wzAdv.setPublishingType(1);
        wzAdv.setModifierId(ShiroKit.getUser().getId());
        wzAdv.setModifierName(ShiroKit.getUser().getName());
        wzAdv.setCreateTime(new Date());
        wzAdvService.insert(wzAdv);

        //改变数据状态


//        List<PfFile> list = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",wzAdv.getCoverUrl()));
//        list.get(0).setStatus(2);
//        pfFileMapper.updateById(list.get(0));

        return super.SUCCESS_TIP;
    }

    /**
     * 删除广告
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Long wzAdvId) {
        WzAdv adv = wzAdvService.selectById(wzAdvId);
        if(adv.getStatus() == 1 || adv.getStatus() == 3){
            wzAdvService.deleteById(wzAdvId);
            return SUCCESS_TIP;
        }else{
            return SUCCESS_TIP.fail("只有编辑中和审核驳回才能删除!");
        }
    }

    /**
     * 广告提交审核
     */
    @RequestMapping(value = "/checkAdv")
    @ResponseBody
    public Object checkAdv(@RequestParam Long wzAdvId) {
        WzAdv adv = wzAdvService.selectById(wzAdvId);
        if(adv.getStatus() == 1 || adv.getStatus() == 3){
            adv.setStatus(2);
            wzAdvService.updateById(adv);
            return SUCCESS_TIP;
        }else{
            return SUCCESS_TIP.fail("只有编辑中的才能提交审核!");
        }
    }

    /**
     * 广告发布
     */
    @Transactional
    @RequestMapping(value = "/release")
    @ResponseBody
    public Object release(@RequestParam Long wzAdvId) {
        WzAdv adv = wzAdvService.selectById(wzAdvId);
        List<WzUser> users = userMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",adv.getUserCode()));
        if(users.get(0).getCashBalance() < (adv.getExpense()+adv.getTotalReward())){
            return SUCCESS_TIP.fail("商户余额不足!发布费用："+(adv.getExpense()+adv.getTotalReward())*0.01+",商户余额:"+users.get(0).getCashBalance()*0.01);
        }
        if(adv.getStatus() == 4){
            //修改广告状态
            adv.setStatus(5);
            wzAdvService.updateById(adv);
            //修改商家问卷状态
            if(adv.getAdvQuestionnaireId() != null){
                WzQuestionnaire questionnaire = questionnaireMapper.selectById(adv.getAdvQuestionnaireId());
                questionnaire.setStatus(6);
                questionnaireMapper.updateById(questionnaire);
            }
            //修改广告问题状态
            if(adv.getAdvQuestionId() != null){
                WzQuestionnaire questionnaire = questionnaireMapper.selectById(adv.getAdvQuestionId());
                questionnaire.setStatus(6);
                questionnaireMapper.updateById(questionnaire);
            }
            //修改用户信息
            users.get(0).setCashBalance(users.get(0).getCashBalance() - (adv.getExpense()+adv.getTotalReward()));
            userMapper.updateById(users.get(0));
            //保存广告用户
            List<WzUser> userList = new ArrayList<>();
            List<WzUser> userList1 = new ArrayList<>();
            //城市筛选
            List<PfOpenCity> openCities = openCityMapper.selectList(new EntityWrapper<PfOpenCity>().eq("ad_code",adv.getScreenCity()));
            if(openCities.get(0).getLevel() == 2){
                List<PfOpenCity> openCitieList = openCityMapper.selectList(new EntityWrapper<PfOpenCity>().eq("father_id",openCities.get(0).getId()));
                for(PfOpenCity openCity:openCitieList){
                    List<WzUser> users1 = userMapper.selectList(new EntityWrapper<WzUser>().eq("ad_code",openCity.getAdCode()));
                    userList.addAll(users1);
                }
            }else{
                userList = userMapper.selectList(new EntityWrapper<WzUser>().eq("ad_code",adv.getScreenCity()));
            }
            //性别筛选
            if(adv.getScreenGender() != 0){
                for(WzUser user:userList){
                    if(user.getGender() == adv.getScreenGender()){
                        userList1.add(user);
                    }
                }
                userList = userList1;
            }
            //保存广告用户
            for(WzUser user:userList){
                WzAdvUser advUser = new WzAdvUser();
                advUser.setAdvId(adv.getAdvId().toString());
                advUser.setCoverUrl(adv.getCoverUrl());
                advUser.setHasDetail(adv.getHasDetail());
                advUser.setSubtype(adv.getSubtype());
                advUser.setTitle(adv.getTitle());
                advUser.setUserCode(user.getUserCode());
                advUserMapper.insert(advUser);
            }
            return SUCCESS_TIP;
        }else{
            return SUCCESS_TIP.fail("只有审核通过的广告才能发布!");
        }
    }

    /**
     * 修改广告
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(WzAdv wzAdv, HttpServletRequest request){
        wzAdv.setUpdateTime(new Date());
        HttpSession session = request.getSession();
        if (session.getAttribute("picUrl") != null) {
            wzAdv.setCoverUrl(session.getAttribute("picUrl").toString());
        }
        if (session.getAttribute("advId") != null) {
            wzAdv.setAdvId(Long.valueOf(session.getAttribute("advId").toString()));
        }
        if (session.getAttribute("type") != null) {
            wzAdv.setType(Integer.valueOf(session.getAttribute("type").toString()));
        }
        if (session.getAttribute("rewardType") != null) {
            wzAdv.setRewardType(Integer.valueOf(session.getAttribute("rewardType").toString()));
        }
        if (session.getAttribute("screenGender") != null) {
            wzAdv.setScreenGender(Integer.valueOf(session.getAttribute("screenGender").toString()));
        }
        if (session.getAttribute("details") != null) {
            wzAdv.setAdvDetail(session.getAttribute("details").toString());
        }
        wzAdvService.updateById(wzAdv);
        session.removeAttribute("picUrl");
        session.removeAttribute("advId");
        session.removeAttribute("type");
        session.removeAttribute("rewardType");
        session.removeAttribute("screenGender");
        session.removeAttribute("details");
        return super.SUCCESS_TIP;
    }

    /**
     * 广告详情
     */
    @RequestMapping(value = "/detail/{wzAdvId}")
    @ResponseBody
    public Object detail(@PathVariable("wzAdvId") Integer wzAdvId) {
        return wzAdvService.selectById(wzAdvId);
    }

}
